//
//  MWDetailInfoViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/31.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
import Popover
class MWDetailInfoViewController: BaseLcController {
    
    enum ProjectStyle:Int{
        case current = 0
        case nocurrent = 1
        case noone = 2
    }
    
    var selectItem:Int?{
        get{
            return 0
        }
        set(newValue){
            print("\(newValue)")
        }
    }
    //班组列表数据
    var bzList = [LCClassListModel]()

    var isSelect = false
    var isDefault = ProjectStyle.current
    fileprivate var mwDetailInfoModel,subDetailModel:MWDetailinfoModel?
    
    var reFreshData:((Bool) -> Void)? = nil
    @IBOutlet weak var underlineView: UIView!
    @IBOutlet weak var projectName: UIButton!
    
    @IBOutlet weak var personIcon: UIImageView!
    
    @IBOutlet weak var personName: UILabel!
    
    @IBOutlet weak var workNum: UILabel!
    
    
    @IBOutlet weak var sexLabel: UILabel!
    
    
    @IBOutlet weak var ageLabel: UILabel!
    
   
    @IBOutlet weak var certificationNum: UILabel!
    
    @IBOutlet weak var detailAdress: UILabel!
    
    @IBOutlet weak var workSort: UILabel!
    
    @IBOutlet weak var classTeam: UILabel!
    
    @IBOutlet weak var attendanceTime: UILabel!
    
    @IBOutlet weak var hourBounce: UILabel!
    
    @IBOutlet weak var phoneView: UIView!
    
    @IBOutlet weak var phoneLabel: UILabel!
    
    @IBOutlet weak var workTypeButton: UIButton!
    
    @IBOutlet weak var classSelectButton: UIButton!
    
    @IBOutlet weak var selectTimeBtn: UIButton!
    @IBOutlet weak var launceTextField: UITextField!
    
    @IBOutlet weak var checkTrackButton: UIButton!
    @IBOutlet weak var reviseButton: UIButton!
    fileprivate var hourSalary:Float?
    fileprivate var workTypeID:String?
    fileprivate var workGroupID:String?
    fileprivate var workTimeQuantumID:String?
    fileprivate var popover: Popover!
    //var currentInfo: MWCurrentLocationModel?
    //var currentProject: LCProjectListModel?
    var isZG:Bool?//是否在岗
    var MigrantWorkerID:String?//在职民工
    var DemandBaseMigrantWorkerID:String?//在岗民工
    var currentProjectName:String?//项目名称
    var currentProjectId:String?//项目的ID
    var LocateTime:String?//轨迹上传时间
    var ProjectRange:[CLLocationCoordinate2D]?//项目围栏
    var isBlackPerson = false //是否属于黑名单
    var emptyData = [String:Any]()
    var gzArray = [(String,String,String)]()
    var timeNameArray = [(String,String,String)]()
    var itemBzArray = [(String,String,String)]()
    
    var isHideGj:Bool?{
        get{
            return true
        }
        set(newValue){
            self.checkTrackButton.isHidden = newValue ?? false
            self.checkTrackButton.isUserInteractionEnabled = !(newValue ?? false)
        }
    }
    
    lazy var leavePersonDialog:CustomDialog = {
        var view = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要删除该民工吗？删除之后将会丢失他的个人资料，请谨慎！", _submitclick: {
            self.leavePersonDialog.dismiss()
            
            guard let accountId = WWUser.sharedInstance.accountId else{
                return
            }
            guard let MigrantWorkerID : String = self.mwDetailInfoModel?.MigrantWorkerID else {
                return
            }
            let migrantWorkerIDList = [MigrantWorkerID]
            MWApiMainManager.request(.SetMigrantWorkerDelete(migrantWorkerIDList: migrantWorkerIDList as NSArray, isSingle: false, AccountId: accountId)) { (result) in
                if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        
                        return
                    }
                    print(jsonString)
                    guard let message : String = jsonString["Msg"] as? String else{
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        QWTextonlyHud(message, target: self.view)
                        return
                    }
                    QWTextonlyHud("设置离职/删除成功！", target: self.view)
                    /*if self.reFreshData != nil{
                        self.reFreshData!(true)
                    }
                    
                    
                    
                    self.navigationController?.popViewController(animated: true)*/
                    
                    
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                        
                        var vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2]
                        if vc is BlackPersonController{
                            (vc as? BlackPersonController)?.getData()
                        }else if vc is LCSignViewController{
                            (vc as? LCSignViewController)?.refreshRequest()
                        }else if vc is LCOffLineViewController{
                            (vc as? LCOffLineViewController)?.setupMWLocationData()
                        }else if vc is BlackPersonController{
                            (vc as? BlackPersonController)?.refresh()
                        }else if vc is WorkerOnJobViewController{
                            (vc as? WorkerOnJobViewController)?.setupOtherWNGData()
                        }
                        self.navigationController?.popViewController(animated: true)
                        
                        
                    })
                    
                }
            }
            
        })
        
        return view
    }()
    
    
    lazy var blackPersonDialog:CustomDialog = {
        var str:String?
        if self.isBlackPerson{
            str = "确定要将该民工移出黑名单吗？"
        }else{
            str = "确定要将该民工加入黑名单吗？之后他将无法在本公司上岗！"
        }
        var view = CustomDialog(frame: CGRect.zero, _title: "提示", _status: str ?? "", _submitclick: {
            self.blackPersonDialog.dismiss()
            guard let accountId = WWUser.sharedInstance.accountId else{
                return
            }
            guard let MigrantWorkerID : String = self.mwDetailInfoModel?.MigrantWorkerID else {
                return
            }
            QWTextWithStatusHud("正在处理...", target: self.view)
            if self.isBlackPerson{
                var params:[String:Any] = ["MigrantWorkerID":self.MigrantWorkerID ?? ""]
                MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .BlackPersonOut, params: &params, type: BlackPersonOut.self, success: { (bean,_) in
                    QWHudDiss(self.view)
                    guard var data = bean as? BlackPersonOut else{
                        return
                    }
                    if data.State == "OK"{
                        QWTextonlyHud("操作成功", target: self.view)
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                            
                            var vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2]
                            if vc is BlackPersonController{
                                (vc as? BlackPersonController)?.getData()
                            }else if vc is LCSignViewController{
                                (vc as? LCSignViewController)?.refreshRequest()
                            }else if vc is LCOffLineViewController{
                                (vc as? LCOffLineViewController)?.setupMWLocationData()
                            }else if vc is WorkerOnJobViewController{
                                (vc as? WorkerOnJobViewController)?.setupOtherWNGData()
                            }
                            
                            /*guard var vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2] as? BlackPersonController else{
                                self.navigationController?.popViewController(animated: true)
                                return
                            }
                            vc.getData()*/
                            self.navigationController?.popViewController(animated: true)
                            
                            
                        })
                        
                    }else{
                        QWTextonlyHud(data.Msg ?? "操作失败请重试", target: self.view)
                    }
                    
                }, error: { (error) in
                    QWHudDiss(self.view)
                    QWTextonlyHud("数据异常，请重试", target: self.view)
                })
                
            }else{
                let migrantWorkerIDList = [MigrantWorkerID]
                MWApiMainManager.request(.SetMigrantWorkerToBlankList(migrantWorkerIDList: migrantWorkerIDList as NSArray, isSingle: false, AccountId: accountId)) { (result) in
                    QWHudDiss(self.view)
                    if case let .success(response) = result {
                        guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                            return
                        }
                        print(jsonString)
                        guard let message : String = jsonString["Msg"] as? String else{
                            return
                        }
                        guard (jsonString["State"]) as! String == "OK" else{
                            QWTextonlyHud(message, target: self.view)
                            return
                        }
                        QWTextonlyHud("已将民工拉入黑名单！", target: self.view)
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                            
                            var vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2]
                            if vc is BlackPersonController{
                                (vc as? BlackPersonController)?.getData()
                            }else if vc is LCSignViewController{
                                (vc as? LCSignViewController)?.refreshRequest()
                            }else if vc is LCOffLineViewController{
                                (vc as? LCOffLineViewController)?.setupMWLocationData()
                            }else if vc is WorkerOnJobViewController{
                                (vc as? WorkerOnJobViewController)?.setupOtherWNGData()
                            }
                            
                            /*guard var vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2] as? BlackPersonController else{
                             self.navigationController?.popViewController(animated: true)
                             return
                             }
                             vc.getData()*/
                            self.navigationController?.popViewController(animated: true)
                            
                            
                        })
                        
                        //self.reFreshData!(true)
                        //self.navigationController?.popViewController(animated: true)
                    }
                }
            }
        })
        return view
    }()
    
    
    @IBAction func checkTrackClick(_ sender: Any) {
        
        var vc = WorkGuiJiControllerViewController(nibName: "WorkGuiJiControllerViewController", bundle: nil)
        //vc.MarketSupplyBaseID = self.MigrantWorkerID ?? ""
        vc.DemandBaseMigrantWorkerID = self.DemandBaseMigrantWorkerID ?? ""
        vc.LocateTime = self.LocateTime
        vc.MarketSupplyBaseID = self.currentProjectId ?? ""
        vc.ProjectRange = self.ProjectRange ?? [CLLocationCoordinate2D]()
        
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    @IBAction func btnClick(_ sender:UIButton){
        switch sender.tag {
        case 0://工种
            var vc = SelectListDialog()//SelectListDialog(nibName: "SelectListDialog", bundle: nil)
            vc.titleStr = "选择工种"
            vc.modalPresentationStyle = .overCurrentContext
            vc.selectBack = {
                index in
                self.workSort.text = self.gzArray[index].0
                self.workTypeID = self.gzArray[index].2
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(self.gzArray)
            break
        case 1://班组
            var vc = SelectListDialog(nibName: "SelectListDialog", bundle: nil)
            vc.widthDelay = 0.8
            vc.modalPresentationStyle = .overCurrentContext
            //vc.setContentWidth(0.8)
            vc.titleStr = "选择班组"
            vc.selectBack = {
                index in
                self.classTeam.text = self.bzList[index].WorkGroupName ?? ""
                self.workGroupID = self.bzList[index].ID ?? ""
                self.attendanceTime.text = self.bzList[index].WorkTimeQuantum ?? ""
                self.workTimeQuantumID = self.bzList[index].WorkTimeQuantumID ?? ""
                self.selectTimeBtn.isHidden = true
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(self.itemBzArray)
            break
        case 2://时段
            var vc = SelectListDialog()//(nibName: "SelectListDialog", bundle: nil)
            vc.modalPresentationStyle = .overCurrentContext
            vc.titleStr = "选择时段"
            vc.selectBack = {
                index in
                self.attendanceTime.text = self.timeNameArray[index].1
                self.workTimeQuantumID = self.timeNameArray[index].2
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(self.timeNameArray)
            break
        case 3://项目选择
            guard var listdata = self.mwDetailInfoModel?.demandBaseList else{
                QWTextonlyHud("暂无数据", target: self.view)
                return
            }
            var vc = WorkerProjectController()
            //vc.demandBaseList = listdata
            vc.modalPresentationStyle = .overCurrentContext
            vc.backData = { index in
                print("\(index)")
                self.mwDetailInfoModel?.demandBaseList![index]
                self.isZG = true
                self.isSelect = true
                self.DemandBaseMigrantWorkerID = self.mwDetailInfoModel?.demandBaseList![index].object(forKey: "DemandBaseMigrantWorkerID") as? String ?? ""
                var title = self.mwDetailInfoModel?.demandBaseList![index].object(forKey: "ProjectName") as? String ?? ""
                //self.setupMigrantWorkerInfoData()
                self.projectName.setTitle(title, for: .normal)
                self.subDetailModel = self.mwDetailInfoModel
                self.resetDic((self.subDetailModel?.demandBaseList![index])!)
                self.mwDetailInfoModel = self.subDetailModel
                self.setupUIWithData()
                
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(listdata)
            break
        default:
            break
        }
    }
    
    lazy var tap:UITapGestureRecognizer = {
        var t = UITapGestureRecognizer(target: self, action: #selector(callPhone(_:)))
        t.numberOfTouchesRequired = 1
        t.numberOfTapsRequired = 1
        return t
    }()
    
    lazy var headTap:UITapGestureRecognizer = {
        var t = UITapGestureRecognizer(target: self, action: #selector(headImg(_:)))
        t.numberOfTouchesRequired = 1
        t.numberOfTapsRequired = 1
        return t
    }()
    
    @objc func headImg(_ sender:UIGestureRecognizer){
        print("--")
        var headurl = ImageUrlPrefix + (self.mwDetailInfoModel?.PhotoPath)!
        var vc = HeadViewController()
        vc.setHeadImg(imgpath: headurl)
        vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: true, completion: nil)
        
    }
    
    @objc func callPhone(_ sender:UIGestureRecognizer){
        guard let tel = self.mwDetailInfoModel?.Phone else{
            return
        }
        UIApplication.shared.openURL(URL(string: "telprompt:\(tel)")!)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        (UIApplication.shared.delegate as? AppDelegate)?.stopIQKeyboardManager()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        (UIApplication.shared.delegate as? AppDelegate)?.startIQKeyboardManager()
    }
    
    @objc func transformView(_ aNSNotification:Notification){
//        获取键盘弹出前的Rect
//        NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
//        CGRect beginRect=[keyBoardBeginBounds CGRectValue];
//
//        获取键盘弹出后的Rect
//        NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
//        CGRect  endRect=[keyBoardEndBounds CGRectValue];
//
//        获取键盘位置变化前后纵坐标Y的变化值
//        CGFloat deltaY=endRect.origin.y-beginRect.origin.y;
//        NSLog(@"看看这个变化的Y值:%f",deltaY);
        
        let keyBoardBeginBounds = aNSNotification.userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue
        let beginRect = keyBoardBeginBounds?.cgRectValue
        let keyBoardEndBounds = aNSNotification.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue
        let endRect = keyBoardEndBounds?.cgRectValue
        var deltaY = (endRect?.origin.y)!-(beginRect?.origin.y)! > 0 ? 0:(endRect?.origin.y)!-(beginRect?.origin.y)!
        print("\(deltaY)")
        UIView.animate(withDuration: 0.25, animations: {
            //[self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)];
            //self.view.frame(forAlignmentRect: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y+deltaY, width: self.view.frame.size.width, height: self.view.frame.size.height))
            self.view.transform = CGAffineTransform(translationX: 0, y: deltaY)
            
            
        }, completion: nil)
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 15, height: 40)
        btn.setImage(UIImage(named: "more"), for: UIControlState.normal)
        btn.imageView?.contentMode = .center
        btn.addTarget(self, action: #selector(rightBarButtonItemClick), for: .touchUpInside)
        let rightBtn = UIBarButtonItem(customView: btn)
        
        self.navigationItem.rightBarButtonItem = rightBtn
        self.personIcon.layer.cornerRadius = self.personIcon.frame.height/2;
        self.personIcon.layer.masksToBounds = true
        self.launceTextField.isEnabled = false
        
        NotificationCenter.default.addObserver(self, selector: #selector(transformView(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //self.currentProject?.ProjectName ?? "暂时无法获取项目名"
        let phoneTap = UITapGestureRecognizer(target: self, action: #selector(phoneDiaClick(_:)))
        self.reviseButton.angle = 5
        self.phoneView.addGestureRecognizer(phoneTap)
        self.setupMigrantWorkerInfoData()
        self.getGzList()
        self.phoneView.addGestureRecognizer(self.tap)
        self.projectName.tag = 3
        self.personIcon.isUserInteractionEnabled = true
        self.personIcon.addGestureRecognizer(self.headTap)
        
        switch self.isDefault {
        case .current:
            if self.isBlackPerson{
                self.projectName.setTitle("", for: .normal)
            }else{
                self.projectName.setTitle(self.currentProjectName ?? "", for: .normal)
                self.projectName.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
            }
            
            //self.projectName.text = self.currentProjectName ?? ""
            break
        case .nocurrent:
            //self.projectName.setTitle("可选项目", for: .normal)
            self.projectName.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
            break
        case .noone:
            self.projectName.setTitle("暂无", for: .normal)
            break
        default:
            break
        }
    }
    
    @objc fileprivate func rightBarButtonItemClick(){
            let startPoint = CGPoint(x: SCREEN_WIDTH - 40, y: 64)
            var viewHeight = CGFloat(132)
            if self.isBlackPerson{
                viewHeight = viewHeight/2
            }
            let detailInfoView = DetailInfoView(frame: CGRect(x: 0, y: 10, width: 90, height: viewHeight))
            detailInfoView.isBlack = self.isBlackPerson
            if !self.isBlackPerson{
                detailInfoView.joinProject.addTarget(self, action: #selector(joinProjectClick), for: .touchUpInside)
                detailInfoView.postAdjust.addTarget(self, action: #selector(postAdjustClick), for: .touchUpInside)
            }else{
                detailInfoView.joinBlackList.setTitle("移出黑名单", for: UIControlState.normal)
            }
        
            detailInfoView.quitDelete.addTarget(self, action: #selector(quitDeleteClick), for: .touchUpInside)
            detailInfoView.joinBlackList.addTarget(self, action: #selector(joinBlackListClick), for: .touchUpInside)
           self.popover = Popover()
           popover.show(detailInfoView, point: startPoint)
    }
    
    @objc fileprivate func joinProjectClick(){
        let joinProjectSelect = JoinProjectSelectViewController(nibName: "JoinProjectSelectViewController", bundle: nil)
        joinProjectSelect.currentInfo = self.mwDetailInfoModel
        self.navigationController?.pushViewController(joinProjectSelect, animated: true)
        self.popover.dismiss()
    }
    @objc fileprivate func postAdjustClick(){
        if self.classTeam.text == "无班组归属"{
            self.selectTimeBtn.isHidden = false
        }else{
            self.selectTimeBtn.isHidden = true
        }
        
        if self.isDefault == .noone{
            self.classSelectButton.isHidden = true
        }else{
            self.classSelectButton.isHidden = false
        }
        
        self.checkTrackButton.isHidden = true
        self.phoneView.isHidden = true
        self.reviseButton.isHidden = false
        self.workTypeButton.isHidden = false
        //self.classSelectButton.isHidden = false
        self.launceTextField.isEnabled = true
        self.launceTextField.textColor = UIColor.black
        //self.launceTextField.becomeFirstResponder()
        self.underlineView.backgroundColor = UIColor.init(red: 0.46, green: 0.82, blue: 0.64, alpha: 1)
        self.popover.dismiss()
    }
    @objc fileprivate func quitDeleteClick(){
        self.popover.dismiss()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            self.leavePersonDialog.show()
        }
        
    
    }
    @objc fileprivate func joinBlackListClick(){
        self.popover.dismiss()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            self.blackPersonDialog.show()
        }
    }
    @objc fileprivate func phoneDiaClick(_ tap:UITapGestureRecognizer){
       
        
    }
    
    @IBAction func reviseButtonClick(_ sender: Any) {
        if (self.launceTextField.text != nil) {
            self.hourSalary = Float(self.launceTextField.text!)
        }
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let MigrantWorkerID = mwDetailInfoModel?.MigrantWorkerID else {
            return
        }
        guard let a = self.workTypeID else {
            return
        }
        guard let b = self.workTimeQuantumID else {
            return
        }
        guard let c = self.hourSalary else {
            return
        }
        if (self.hourSalary ?? 0) < 5.0 && WorkType == 2{
            QWTextonlyHud("工资不能低于5元/小时", target: self.view)
            return
        }
        
        if (self.hourSalary ?? 0) < 50.0 && WorkType != 2{
            QWTextonlyHud("工资不能低于50元/工", target: self.view)
            return
        }
        
        
        
        print(self.hourSalary)
        print(MigrantWorkerID)
        MWApiMainManager.request(.SetMigrantWorkInfo(MigrantWorkerID: MigrantWorkerID, DemandBaseMigrantWorkerID: self.DemandBaseMigrantWorkerID ?? "", workTypeID: self.workTypeID!, workGroupID: self.workGroupID ?? "", workTimeQuantumID: self.workTimeQuantumID!, hourSalary: self.hourSalary!, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    return
                }
                print(jsonString)
                guard let message : String = jsonString["Msg"] as? String else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    QWTextonlyHud(message, target: self.view)
                    return
                }
                QWTextonlyHud("岗位调整成功", target: self.view)
                self.checkTrackButton.isHidden = false
                self.phoneView.isHidden = false
                self.reviseButton.isHidden = true
                self.workTypeButton.isHidden = true
                self.selectTimeBtn.isHidden = true
                self.classSelectButton.isHidden = true
                self.launceTextField.isEnabled = false
                self.launceTextField.textColor = UIColor.lightGray
                self.underlineView.backgroundColor = UIColor.black
                self.setupMigrantWorkerInfoData()
            }
        }
    
    }
    fileprivate func setupMigrantWorkerInfoData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        QWTextWithStatusHud("正在载入数据...", target: self.view)
        if isZG ?? false{
            MWApiMainManager.request(.GetMigrantWorkerInfo(MigrantWorkerID: self.MigrantWorkerID ?? "", DemandBaseMigrantWorkerID: self.DemandBaseMigrantWorkerID ?? "", AccountId: accountId)) { (result) in
                QWHudDiss(self.view)
                switch result{
                case let .success(response):
                    var resultstr = String.init(data: response.data, encoding: String.Encoding.utf8)
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                    guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                        return
                    }
                    print(jsonString)
                    //self.attendceTimeArray = Mapper<LCAtteendceTimeModel>().mapArray(JSONObject: itemsArray)!
                    self.mwDetailInfoModel = Mapper<MWDetailinfoModel>().map(JSONObject: resultDic)
                    if self.isDefault == .current{
                        self.mwDetailInfoModel?.ProjectName = ProjectName
                    }else if self.isDefault == .nocurrent{
                        self.mwDetailInfoModel?.ProjectName = "项目名"
                    }
                    for item in (self.mwDetailInfoModel?.demandBaseList)!{
                        if item["MarketSupplyBaseID"] as? String == ProjectId{
                            self.mwDetailInfoModel?.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            self.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            
                        }
                        if self.isDefault != .current{
                            if item.object(forKey: "IsAppSelected") as? Double == 1{
                                self.subDetailModel = self.mwDetailInfoModel//MWDetailinfoModel.init(map: Map.init(mappingType: .toJSON, JSON: [String:Any]()))
                                self.resetDic(item)
                                
                                
                            }
                        }
                        
                    }
                    if !self.isSelect{
                        if self.isDefault == .nocurrent{
                            if self.subDetailModel != nil{
                                self.mwDetailInfoModel = self.subDetailModel
                            }
                            
                        }
                    }
                    
                    
                    
                    self.setupUIWithData()
                    break
                case .failure(_):
                    break
                }
            }
        }else{
            MWApiMainManager.request(.GetMigrantWorkerInfo(MigrantWorkerID: self.MigrantWorkerID ?? "", DemandBaseMigrantWorkerID: "", AccountId: accountId)) { (result) in
                
                switch result{
                case let .success(response):
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                    guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                        return
                    }
                    print(jsonString)
                    //self.attendceTimeArray = Mapper<LCAtteendceTimeModel>().mapArray(JSONObject: itemsArray)!
                    self.mwDetailInfoModel = Mapper<MWDetailinfoModel>().map(JSONObject: resultDic)
                    
                    /*for item in (self.mwDetailInfoModel?.demandBaseList)!{
                        if item["MarketSupplyBaseID"] as? String == ProjectId{
                            self.mwDetailInfoModel?.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            self.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            break
                        }
                    }*/
                    
                    //--------------
                    
                    if self.isDefault == .current{
                        self.mwDetailInfoModel?.ProjectName = ProjectName
                    }else if self.isDefault == .nocurrent{
                        self.mwDetailInfoModel?.ProjectName = "项目名"
                    }
                    for item in (self.mwDetailInfoModel?.demandBaseList)!{
                        if item["MarketSupplyBaseID"] as? String == ProjectId{
                            self.mwDetailInfoModel?.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            self.DemandBaseMigrantWorkerID = item["DemandBaseMigrantWorkerID"] as? String
                            
                        }
                        if self.isDefault != .current{
                            if item.object(forKey: "IsAppSelected") as? Double == 1{
                                self.subDetailModel = self.mwDetailInfoModel//MWDetailinfoModel.init(map: Map.init(mappingType: .toJSON, JSON: [String:Any]()))
                                self.resetDic(item)
                                
                                /*self.subDetailModel?.Address = self.mwDetailInfoModel?.Address
                                 self.subDetailModel?.Age = self.mwDetailInfoModel?.Age
                                 self.subDetailModel?.IDCard = self.mwDetailInfoModel?.IDCard
                                 self.subDetailModel?.Phone = self.mwDetailInfoModel?.Phone*/
                                
                            }
                        }
                        
                    }
                    if !self.isSelect{
                        if self.isDefault == .nocurrent{
                            if self.subDetailModel != nil{
                                self.mwDetailInfoModel = self.subDetailModel
                            }
                            
                        }
                    }
                    
                    
                    //---------------
                    
                    self.setupUIWithData()
                    QWHudDiss(self.view)
                    break
                case .failure(_):
                    QWHudDiss(self.view)
                    break
                }
            }
        }
        
    }
    
    func resetDic(_ item:NSDictionary){
        self.subDetailModel?.ChangeDaySalary = item.object(forKey: "ChangeDaySalary") as? Double
        self.subDetailModel?.ChangeHourSalary = item.object(forKey: "ChangeHourSalary") as? Double
        self.subDetailModel?.DaySalary = item.object(forKey: "DaySalary") as? Double
        self.subDetailModel?.DemandBaseMigrantWorkerID = item.object(forKey: "DemandBaseMigrantWorkerID") as? String ?? ""
        self.subDetailModel?.HourSalary = item.object(forKey: "HourSalary") as? String
        self.subDetailModel?.MarketSupplyBaseID = item.object(forKey: "MarketSupplyBaseID") as? String
        self.subDetailModel?.MigrantWorkType = item.object(forKey: "MigrantWorkType") as? NSDictionary
        self.subDetailModel?.MigrantWorkerID = item.object(forKey: "MigrantWorkerID") as? String
        self.subDetailModel?.ProjectName = item.object(forKey: "ProjectName") as? String
        self.subDetailModel?.WorkGroup = item.object(forKey: "WorkGroup") as? NSDictionary
        self.subDetailModel?.WorkHours = item.object(forKey: "WorkHours") as? String
        self.subDetailModel?.WorkTimeQuantum = item.object(forKey: "WorkTimeQuantum") as? NSDictionary
        self.subDetailModel?.demandBaseList = self.mwDetailInfoModel?.demandBaseList
    }
    
    
    fileprivate func setupUIWithData(){
        
        guard (mwDetailInfoModel != nil) else{
            return
        }
        if ((mwDetailInfoModel?.Name) != nil) {
            self.navigationItem.title = mwDetailInfoModel?.Name
        }
        if self.isDefault != .noone && !self.isBlackPerson{
            self.projectName.setTitle(self.mwDetailInfoModel?.ProjectName, for: .normal)
        }
       //self.hourSalary = mwDetailInfoModel?.HourSalary
       self.personName.text = self.mwDetailInfoModel?.Name
        if mwDetailInfoModel?.Sex == 0{
            self.sexLabel.text = "男"
        }else{
            self.sexLabel.text = "女"
        }
        
        self.phoneLabel.text = self.mwDetailInfoModel?.Phone ?? ""
        
        self.detailAdress.text = mwDetailInfoModel?.Address ?? "暂无"
        if ((mwDetailInfoModel?.Age) != nil) {
            self.ageLabel.text = String(mwDetailInfoModel!.Age!) + "岁"
        }else{
            self.ageLabel.text = "未知"
        }
        self.workNum.text = mwDetailInfoModel?.MigrantWorkerNo
        
        if ((mwDetailInfoModel?.IDCard) != nil) {
            
            self.certificationNum.text = mwDetailInfoModel!.IDCard!
            
        }else{
            self.certificationNum.text = "未知"
            
        }
        let migrantWorkTypeDic = mwDetailInfoModel?.MigrantWorkType
        
        if let workSortName : String = migrantWorkTypeDic?["WorkType"] as? String {
            
            self.workSort.text = workSortName
        }else{
            self.workSort.text = "普工"
        }
        self.workTypeID = (migrantWorkTypeDic?["ID"] as! String)
        
        let workGroup = mwDetailInfoModel?.WorkGroup
        if let workGroupName : String = workGroup?["WorkGroupName"] as? String {
            if workGroupName == ""{
                self.classTeam.text = "无班组归属"
            }else{
            self.classTeam.text = workGroupName
            }
        }else{
            self.classTeam.text = "无班组归属"
        }
        self.workGroupID = (workGroup?["ID"] as? String)
        let workTimeQuantum = mwDetailInfoModel?.WorkTimeQuantum
        if let workTimeQuantumName : String = workTimeQuantum?["WorkTimeQuantumName"] as? String {
            self.attendanceTime.text = workTimeQuantumName
        }else{
            self.classTeam.text = "未设置"
        }
        self.workTimeQuantumID = (workTimeQuantum?["ID"] as? String)
        if ((mwDetailInfoModel?.PhotoPath) != nil) {
            self.personIcon.kf.setImage(with: URL.init(string: (ImageUrlPrefix + (mwDetailInfoModel?.PhotoPath)!)), placeholder: UIImage(named: "scene_touxiang"), options: nil, progressBlock: nil, completionHandler: nil)
        }
        if WorkType == 2{
            if mwDetailInfoModel!.ChangeHourSalary ?? 0 > 0 {
                self.launceTextField.text = String((mwDetailInfoModel!.ChangeHourSalary ?? 0.0))
            }else{
                let str = String.init(format: "%.2f", Double(mwDetailInfoModel?.HourSalary ?? "0.0")!)
                self.launceTextField.text = str
            }
            
            self.hourBounce.text = "元/小时"
        }else{
            if mwDetailInfoModel?.ChangeDaySalary ?? 0 > 0{
                self.launceTextField.text = String((mwDetailInfoModel?.ChangeDaySalary ?? 0.0))
            }else{
                let str = String.init(format: "%.2f", mwDetailInfoModel?.DaySalary ?? 0.00)
                self.launceTextField.text = str
            }
            
            self.hourBounce.text = "元/工"
        }
        
    }
}


extension MWDetailInfoViewController{
    
    //获取工种
    func getGzList(){
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GZLIST, params: &self.emptyData, type: GZTypeList.self, success: { (bean,_) in
            guard let data = bean as? GZTypeList else{
                return
            }
            data.Result?.forEach({ (item) in
                self.gzArray.append((item.WorkType ?? "","",item.ID ?? ""))
            })
            self.getTimeList()
            self.setupClassData()
        }) { (error) in
            
        }
    }
    //获取时间列表
    func getTimeList(){
        var params:[String:Any] = ["start":"0","limit":"100","orderManagerConfigId":"862BCA72-AB8A-B2ED-520B-A14C2BE74850"]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQSJLIST, params: &params, type: KQSJList.self, success: { (bean,_) in
            guard let data = bean as? KQSJList else{
                return
            }
            
            data.Result?.Items?.forEach({ (item) in
                var str = ""
                if (item.BeginTime ?? "").count > 16{
                    str += (item.BeginTime ?? "").getSubstring(11, end: 16)
                }
                str += "-"
                if item.IsLastDay ?? false {
                    str += "第二天"
                }
                if (item.EndTime ?? "").count > 16{
                    str += (item.EndTime ?? "").getSubstring(11, end: 16)
                }
                self.timeNameArray.append((item.WorkTimeQuantumName ?? "",str,item.ID ?? ""))
            })
        }) { (error) in
            
        }
    }
    
    //获取班组
    fileprivate func setupClassData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let MarketSupplyBaseID = ProjectId else{
            return
        }
        LCAPiMainManager.request(.CheckClassList(MarketSupplyBaseID: MarketSupplyBaseID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                print(jsonString)
                self.bzList.removeAll()
                let resultArray : NSArray = jsonString["Result"] as! NSArray
                var array : [LCClassListModel] = Mapper<LCClassListModel>().mapArray(JSONObject: resultArray)!
                self.bzList.append(contentsOf: array)
                array.forEach({ (item) in
                    self.itemBzArray.append((item.WorkGroupName ?? "",item.WorkTimeQuantum ?? "",item.ID ?? ""))
                })
            }
            
        }
        
    }
    //民工项目
}
